# -*- coding: utf-8 -*-

from common import *
from dragline import *
from glahf import glahf, faceutil
from operator import itemgetter
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import *

import re
import util


DICT = {chr(i-1+ord('A')):i for i in xrange(1,27)}

ARR = [chr(i-1+ord('A')) for i in xrange(1,27)] + \
    [chr(i-1+ord('A')) + chr(j-1+ord('A')) for i in xrange(1,27) for j in xrange(1,27)]

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class AnalyseWindow(QtGui.QMainWindow):

    class _Status(object):
        # start and end
        __slots__ = ()
        
        FOCUS = "START"
        # ORIG AND IR
        CURRENT_MODE = "ORIG"

    class InputEdit(QtGui.QLineEdit):
        def __init__(self, parent):
            QtGui.QLineEdit.__init__(self,parent)

        @property
        def key(self):
            return self._key
        @key.setter
        def key(self, value):
            self._key = value

        def mousePressEvent(self, ev):
            AnalyseWindow._Status.FOCUS = self._key

    @property
    def mode(self):
        return self._Status.CURRENT_MODE

    @mode.setter
    def mode(self, value):
        if value in ('ORIG','IR'):
            self._Status.CURRENT_MODE = value
        else:
            raise ValueError("unexpected value")

    @property
    def focus(self):
        return self._Status.FOCUS
        
    @focus.setter
    def focus(self, value):
        if value in ('START', 'END'):
            self._Status.FOCUS = value
        else:
            raise ValueError("unexpected value")

    def __init__(self
            ,parent=None, datas=None, linesArr=None):
        super(AnalyseWindow, self).__init__(parent)
        
        self.focus = "START"
        self.img = None
        self.img_path = None
        self.spliced_img = None
        self.vis = None
        self.clb_gv = 0
        self.__linesArr = linesArr
        self.__vDraglines = []
        self.__hDraglines = []
        self.datas = datas
        self.config = util.load_config()
        self.setupUi(self)
        self.retranslateUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        screen = QtGui.QDesktopWidget().screenGeometry()
        GLOBAL_WIDTH = screen.width()
        GLOBAL_HEIGHT = screen.height()
        self.resize(GLOBAL_WIDTH, GLOBAL_HEIGHT)

        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        font = QtGui.QFont()
        try:
            font.setFamily(_fromUtf8("Microsoft YaHei"))
        except Exception:
            pass
        self.setStyleSheet("QLineEdit{margin-left:20%;margin-right:30%;height:50%;font-size:18px;}")

        self.PREIVIEW_H = GLOBAL_HEIGHT*0.55
        self.PREIVIEW_W = GLOBAL_WIDTH*0.8
        self.PREIVIEW_TOTOP = 20
        self.PREIVIEW_TOLEFT = GLOBAL_WIDTH*0.1

        if not self.datas:
            V = int(self.config["vposcount"])
            H = int(self.config["hposcount"])
        else:
            H = int(self.datas['H'])
            V = int(self.datas['V'])

        voffset = float(self.PREIVIEW_H)/V
        hoffset = float(self.PREIVIEW_W)/H
        
        for i in xrange(1,V+1):
            label = QtGui.QLabel(self.centralwidget)
            label.setGeometry(QtCore.QRect(self.PREIVIEW_TOLEFT-25, 12+i*voffset, 15, 10))
            label.setText(str(i))
        else:
            self.X_VAXIS = str(i)

        for i in xrange(0,H+1):
            label = QtGui.QLabel(self.centralwidget)
            label.setGeometry(QtCore.QRect(self.PREIVIEW_TOLEFT+i*hoffset, 0, 12, 15))
            label.setText(str(ARR[i]))
        else:
            self.X_HAXIS = str(ARR[i])

        QLE_BGSTYLE = "QLineEdit{background: %s;}"
        # 自动输入
        def AutoSetText(hpos,vpos):
            _self = self
            pos = vpos+ARR[int(hpos)]
            if self.focus:
                _self.setCursor(Qt.CrossCursor)
                color = 'red'
                if self.focus == 'START':
                    _self.startpointInput.setText(pos)
                    _self.startpointInput.setStyleSheet(QLE_BGSTYLE %color)
                else:
                    _self.endpointInput.setText(pos)
                    _self.endpointInput.setStyleSheet(QLE_BGSTYLE %color)
                    
        def AutoSetBack():
            _self = self
            if self.focus:
                _self.setCursor(Qt.ArrowCursor)
                color = 'white'
                if self.focus == 'START':
                    _self.startpointInput.setStyleSheet(QLE_BGSTYLE %color)
                else:
                    _self.endpointInput.setStyleSheet(QLE_BGSTYLE %color)

        class PreviewLabel(QtGui.QLabel):
            def __init(self, parent):
                QtGui.QLabel.__init__(self, parent)
                self.hpos = None
                self.vpos = None

            def mousePressEvent(self, ev):
                x = ev.x()
                y = ev.y()
                hpos = int(round(x/float(hoffset)))
                vpos = int(round(y/float(voffset)))
                AutoSetText(str(hpos),str(vpos))

            def mouseReleaseEvent(self, ev):
                AutoSetBack()

            def getpos(self):
            	return (self.hpos, self.vpos)


        # 底部布局
        self.bottomLayoutWidget = QtGui.QWidget(self.centralwidget)
        self.bottomLayoutWidget.setGeometry(QtCore.QRect(0, GLOBAL_HEIGHT*0.6, GLOBAL_WIDTH-10, GLOBAL_HEIGHT*0.3))
        self.bottomLayoutWidget.setObjectName(_fromUtf8("bottomLayoutWidget"))
        self.bottomLayout = QtGui.QHBoxLayout(self.bottomLayoutWidget)
        self.bottomLayout.setObjectName(_fromUtf8("bottomLayout"))

        # 预览标签
        self.previewLabel = PreviewLabel(self.centralwidget)
        self.previewLabel.setGeometry(QtCore.QRect(self.PREIVIEW_TOLEFT, self.PREIVIEW_TOTOP
                                        ,self.PREIVIEW_W, self.PREIVIEW_H))
        self.previewLabel.setScaledContents(True)
        self.previewLabel.setObjectName(_fromUtf8("label"))

        # 自动获取标签
        self.autogetLabel = QtGui.QLabel(self.centralwidget)
        font.setPointSize(18)
        self.autogetLabel.setFont(font)

        self.area_12af_Label = QtGui.QLabel(self.centralwidget)
        self.area_12af_Color = QtGui.QLabel(self.centralwidget)

        self.area_34ef_Label = QtGui.QLabel(self.centralwidget)
        self.area_34ef_Color = QtGui.QLabel(self.centralwidget)

        self.area_45bc_Label = QtGui.QLabel(self.centralwidget)
        self.area_45bc_Color = QtGui.QLabel(self.centralwidget)

        self.area_45de_Label = QtGui.QLabel(self.centralwidget)
        self.area_45de_Color = QtGui.QLabel(self.centralwidget)

        self.area_45ef_Label = QtGui.QLabel(self.centralwidget)
        self.area_45ef_Color = QtGui.QLabel(self.centralwidget)

        self.area_56ef_Label = QtGui.QLabel(self.centralwidget)
        self.area_56ef_Color = QtGui.QLabel(self.centralwidget)

        self.left_avg_Label = QtGui.QLabel(self.centralwidget)
        self.left_avg_Color = QtGui.QLabel(self.centralwidget)
        self.frontal_avg_Label = QtGui.QLabel(self.centralwidget)
        self.frontal_avg_Color = QtGui.QLabel(self.centralwidget)
        self.right_avg_Label = QtGui.QLabel(self.centralwidget)
        self.right_avg_Color = QtGui.QLabel(self.centralwidget)
        self.all_avg_Label = QtGui.QLabel(self.centralwidget)
        self.all_avg_Color = QtGui.QLabel(self.centralwidget)

        self.left_avg_ir_Label = QtGui.QLabel(self.centralwidget)
        self.left_avg_ir_Color = QtGui.QLabel(self.centralwidget)
        self.frontal_avg_ir_Label = QtGui.QLabel(self.centralwidget)
        self.frontal_avg_ir_Color = QtGui.QLabel(self.centralwidget)
        self.right_avg_ir_Label = QtGui.QLabel(self.centralwidget)
        self.right_avg_ir_Color = QtGui.QLabel(self.centralwidget)
        self.all_avg_ir_Label = QtGui.QLabel(self.centralwidget)
        self.all_avg_ir_Color = QtGui.QLabel(self.centralwidget)

        # 框线
        frameStyle = "border:1px solid lightgray;border-radius:5px;opacity:0.5;"
        self.frameLabel1 = QtGui.QWidget(self.centralwidget)
        self.frameLabel1.setStyleSheet(frameStyle)
        self.frameLabel2 = QtGui.QWidget(self.centralwidget)
        self.frameLabel2.setStyleSheet(frameStyle)
        self.frameLabel3 = QtGui.QWidget(self.centralwidget)
        self.frameLabel3.setStyleSheet(frameStyle)

        self.leftLayout = QtGui.QGridLayout()
        self.leftLayout.setObjectName(_fromUtf8("leftLayout"))
        self.leftLayout.addWidget(self.frameLabel1, 0, 0, 11, 3)

        self.posLayout = QtGui.QVBoxLayout()
        self.posLayout.addWidget(self.autogetLabel)
        self.area_12af_Label.setMargin(5)
        self.area_34ef_Label.setMargin(5)
        self.area_45bc_Label.setMargin(5)
        self.area_45de_Label.setMargin(5)
        self.area_45ef_Label.setMargin(5)
        self.area_56ef_Label.setMargin(5)
        self.posLayout.addWidget(self.area_12af_Label)
        self.posLayout.addWidget(self.area_34ef_Label)
        self.posLayout.addWidget(self.area_45bc_Label)
        self.posLayout.addWidget(self.area_45de_Label)
        self.posLayout.addWidget(self.area_45ef_Label)
        self.posLayout.addWidget(self.area_56ef_Label)

        self.colLayout = QtGui.QVBoxLayout()
        self.colLayout.setMargin(5)
        # 腾出对齐
        self.colLayout.addWidget(QtGui.QLabel())
        self.colLayout.addWidget(self.area_12af_Color)
        self.colLayout.addWidget(self.area_34ef_Color)
        self.colLayout.addWidget(self.area_45bc_Color)
        self.colLayout.addWidget(self.area_45de_Color)
        self.colLayout.addWidget(self.area_45ef_Color)
        self.colLayout.addWidget(self.area_56ef_Color)        

        self.autoLayout = QtGui.QVBoxLayout()
        self.autoLayout.setMargin(5)
        self.autoLayout.addWidget(self.left_avg_Label)
        self.autoLayout.addWidget(self.frontal_avg_Label)
        self.autoLayout.addWidget(self.right_avg_Label)
        self.autoLayout.addWidget(self.all_avg_Label)
        self.autoLayout.addWidget(self.left_avg_ir_Label)
        self.autoLayout.addWidget(self.frontal_avg_ir_Label)
        self.autoLayout.addWidget(self.right_avg_ir_Label)
        self.autoLayout.addWidget(self.all_avg_ir_Label)

        self.leftLayout.addLayout(self.posLayout, 0, 0)
        self.leftLayout.addLayout(self.colLayout, 0, 1)
        self.leftLayout.addLayout(self.autoLayout, 0, 2)

        self.bottomLayout.addLayout(self.leftLayout)

        # 平均灰度值标签
        self.grayValueLabel = QtGui.QLabel(self.centralwidget)
        font.setPointSize(25)
        self.grayValueLabel.setFont(font)
        self.grayValueLabel.setObjectName(_fromUtf8("grayValueLabel"))
        # 灰度值结果标签
        self.resultLabel = QtGui.QLabel(self.centralwidget)
        font.setPointSize(16)
        font.setBold(False)
        font.setWeight(50)
        self.resultLabel.setFont(font)
        self.resultLabel.setText(_fromUtf8(""))
        self.resultLabel.setObjectName(_fromUtf8("resultLabel"))
        # 灰度结果
        self.area_sp_Color = QtGui.QLabel(self.centralwidget)

        # 坐标输入
        self.positionLabel = QtGui.QLabel(self.centralwidget)
        font.setPointSize(18)
        self.positionLabel.setFont(font)
        self.positionLabel.setObjectName(_fromUtf8("positionLabel"))

        # 开始坐标标签
        self.startpointLabel = QtGui.QLabel(self.centralwidget)
        font.setPointSize(12)
        self.startpointLabel.setFont(font)
        self.startpointLabel.setObjectName(_fromUtf8("startpointLabel"))
        # 结束坐标标签
        self.endpointLabel = QtGui.QLabel(self.centralwidget)
        self.endpointLabel.setFont(font)
        self.endpointLabel.setObjectName(_fromUtf8("endpointLabel"))
        # 开始坐标输入
        self.startpointInput = self.InputEdit(self.centralwidget)
        self.startpointInput.setObjectName(_fromUtf8("startpointInput"))
        self.startpointInput.key = "START"
        # 结束坐标输入
        self.endpointInput = self.InputEdit(self.centralwidget)
        self.endpointInput.setObjectName(_fromUtf8("endpointInput"))
        self.endpointInput.key = "END"

        # 提示标签
        self.tipLabel = QtGui.QLabel(self.centralwidget)
        self.tipLabel.setFont(font)
        self.tipLabel.setText(_fromUtf8(""))
        self.tipLabel.setObjectName(_fromUtf8("tipLabel"))
        
        # 确定输入按钮
        self.okButton = QtGui.QPushButton(self.centralwidget)
        self.okButton.setObjectName(_fromUtf8("okButton"))
        font.setPointSize(10)
        self.okButton.setFont(font)

        self.centerLayout = QtGui.QGridLayout()
        self.centerLayout.setObjectName(_fromUtf8("centerLayout"))
        self.centerLayout.setSpacing(10)
        self.positionLabel.setMargin(10)
        self.startpointLabel.setMargin(10)
        self.endpointLabel.setMargin(10)
        self.centerLayout.addWidget(self.frameLabel2, 0, 0, 5, 3)
        self.centerLayout.addWidget(self.positionLabel, 0, 0, 2, 1)
        self.centerLayout.addWidget(self.tipLabel, 0, 1, 2, 1)
        self.centerLayout.addWidget(self.startpointLabel, 2, 0, 1, 1)
        self.centerLayout.addWidget(self.endpointLabel, 3, 0, 1, 1)
        self.centerLayout.addWidget(self.startpointInput, 2, 1, 1, 1)
        self.centerLayout.addWidget(self.endpointInput, 3, 1, 1, 1)
        self.centerLayout.addWidget(self.okButton, 4, 1, 1, 1)

        self.bottomLayout.addLayout(self.centerLayout)

        # 退出按钮
        self.exitButton = QtGui.QPushButton(self.centralwidget)
        font.setPointSize(12)
        self.exitButton.setFont(font)
        self.exitButton.setObjectName(_fromUtf8("exitButton"))
        # 分析按钮
        self.lookAnalyseButton = QtGui.QPushButton(self.centralwidget)
        self.lookAnalyseButton.setFont(font)
        self.lookAnalyseButton.setObjectName(_fromUtf8("lookAnalyseButton"))

        # 切换按钮
        self.switchButton = QtGui.QPushButton(self.centralwidget)
        self.switchButton.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.92, GLOBAL_HEIGHT*0.53
                                        ,GLOBAL_WIDTH*0.05, GLOBAL_HEIGHT*0.05))
        self.switchButton.setObjectName(_fromUtf8("okButton"))
        self.switchButton.setFont(font)
        
        self.rightLayout = QtGui.QGridLayout()
        self.rightLayout.setObjectName(_fromUtf8("rightLayout"))
        self.rightLayout.addWidget(self.frameLabel3, 0, 0, 4, 2)
        self.rightLayout.addWidget(self.switchButton, 0, 0, 1, 1)
        self.rightLayout.addWidget(self.lookAnalyseButton, 1, 0, 1, 1)
        self.rightLayout.addWidget(self.exitButton, 2, 0, 1, 1)

        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.addWidget(self.grayValueLabel)
        self.verticalLayout.addWidget(self.resultLabel)
        self.verticalLayout.addWidget(self.area_sp_Color)
        self.rightLayout.addLayout(self.verticalLayout, 0, 1, 3, 1)

        self.bottomLayout.addLayout(self.rightLayout)
        self.bottomLayout.setStretch(0,1)
        self.bottomLayout.setStretch(1,1)
        self.bottomLayout.setStretch(2,1)

        MainWindow.setCentralWidget(self.centralwidget)

        self.connect(self.exitButton,QtCore.SIGNAL('clicked()'),self.returnTo)
        self.connect(self.okButton,QtCore.SIGNAL('clicked()'),self.getPosition)
        self.connect(self.lookAnalyseButton,QtCore.SIGNAL('clicked()'),self.getanalyse)
        self.connect(self.switchButton, QtCore.SIGNAL('clicked()'),self.switchVis)
        self.setAcceptDrops(True)

        if self.__linesArr:
            VLines = [i for i in self.__linesArr if i['y']==0]
            HLines = [i for i in self.__linesArr if i['x']==0]
            VLines = sorted(VLines,key=itemgetter('x'))
            HLines = sorted(HLines,key=itemgetter('y'))

            VKey = [str(i) for i in range(1,len(VLines)+1)]
            HKey = [chr(i-1+ord('a')) for i in range(1,len(HLines)+1)]

            self.LINE_WEIGHT = 5
            for line,key in zip(VLines,VKey):
                pos = (1 + line.get('x'))*self.PREIVIEW_W/3 + self.PREIVIEW_TOLEFT
                dragline = DragLine('', self, 'V')
                dragline.setText(key)
                dragline.info = key
                dragline.callback = self.__closeline_callback
                dragline.xpos = round((pos-self.PREIVIEW_TOLEFT+self.LINE_WEIGHT/2)/float(self.PREIVIEW_W),3)
                dragline.setGeometry(pos, self.PREIVIEW_TOTOP, self.LINE_WEIGHT, self.PREIVIEW_H)
                dragline.setStyleSheet("background-color:red;color:white;")
                self.__vDraglines.append(dragline)

            for line,key in zip(HLines,HKey):
                pos = line.get('y')*self.PREIVIEW_H + self.PREIVIEW_TOTOP
                dragline = DragLine('', self, 'H')
                dragline.setText(key)
                dragline.info = key
                dragline.callback = self.__closeline_callback
                dragline.ypos = round((pos-self.PREIVIEW_TOTOP+self.LINE_WEIGHT/2)/float(self.PREIVIEW_H),3)
                dragline.setGeometry(self.PREIVIEW_TOLEFT, pos, self.PREIVIEW_W, self.LINE_WEIGHT)
                dragline.setStyleSheet("background-color:red;color:white;")
                self.__hDraglines.append(dragline)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def __closeline_callback(self,key):
        def deal_with_line(linesArr):
            __finded = False
            __last_key = None
            __deleted_line = None
            for line in linesArr:
                if __finded is True:
                    line.info = __last_key
                    line.setText(__last_key)
                    __last_key = chr(ord(__last_key)+1)
                if line.info == key and __finded is False:
                    __finded = True
                    __last_key = key
                    __deleted_line = line
            else:
                if __deleted_line in linesArr:
                    linesArr.remove(__deleted_line)
                    return

        deal_with_line(self.__vDraglines)
        deal_with_line(self.__hDraglines)

    def setPath(self, l_path, f_path, r_path):
        self.l_path = l_path
        self.f_path = f_path
        self.r_path = r_path

    def get_auto_results(self):
        # from left to right
        f = self.get_auto_grayvalue
        v_12af = f('1','2','a','f')
        pesudo = glahf.gray_to_pseudo(int(v_12af))
        self.area_12af_Label.setText("12af:"+str(v_12af))
        self.area_12af_Color.setStyleSheet("background-color:rgb%s;" %str(pesudo))

        v_34ef = f('3','4','e','f')
        pesudo = glahf.gray_to_pseudo(int(v_34ef))
        self.area_34ef_Label.setText("34ef:"+str(v_34ef))
        self.area_34ef_Color.setStyleSheet("background-color:rgb%s;" %str(pesudo))

        v_45bc = f('4','5','b','c')
        pesudo = glahf.gray_to_pseudo(int(v_45bc))
        self.area_45bc_Label.setText("45bc:"+str(v_45bc))
        self.area_45bc_Color.setStyleSheet("background-color:rgb%s;" %str(pesudo))

        v_45de = f('4','5','d','e')
        pesudo = glahf.gray_to_pseudo(int(v_45de))
        self.area_45de_Label.setText("45de:"+str(v_45de))
        self.area_45de_Color.setStyleSheet("background-color:rgb%s;" %str(pesudo))
        v_45ef = f('4','5','e','f')

        pesudo = glahf.gray_to_pseudo(int(v_45ef))
        self.area_45ef_Label.setText("45ef:"+str(v_45ef))
        self.area_45ef_Color.setStyleSheet("background-color:rgb%s;" %str(pesudo))

        v_56ef = f('5','6','e','f')
        pesudo = glahf.gray_to_pseudo(int(v_56ef))
        self.area_56ef_Label.setText("56ef:"+str(v_56ef))
        self.area_56ef_Color.setStyleSheet("background-color:rgb%s;" %str(pesudo))

    def get_auto_grayvalue(self,l_line,r_line,up_line,dn_line):
        v_left = None
        v_right = None
        h_up = None
        h_down = None
        for line in self.__vDraglines:
            key = str(line)
            if key == l_line:
                v_left = line
            elif key == r_line:
                v_right = line
        for line in self.__hDraglines:
            key = str(line)
            if key == up_line:
                h_up = line
            elif key == dn_line:
                h_down = line
        if v_left and v_right and h_up and h_down:
            return self.get_sp_grayvalue(v_left,v_right,h_up,h_down)

    def get_sp_grayvalue(self,v_left,v_right,h_up,h_down):
        start_x = v_left.xpos
        end_x = v_right.xpos
        start_y = h_up.ypos
        end_y = h_down.ypos
        grayvalue = glahf.roi_grayvalue(self.img, start_x, end_x, start_y, end_y)
        if self.clb_gv > 0 and self.clb_gv < 255:
            v = 255-self.clb_gv
            grayvalue += v
        return grayvalue

    def dragEnterEvent(self, e):
        e.accept()

    def dropEvent(self, e):
        dragline = e.source()
        position = e.pos()
        if position.x() < self.PREIVIEW_TOLEFT:
            position.setX(self.PREIVIEW_TOLEFT)
        elif position.x() > self.PREIVIEW_W+self.PREIVIEW_TOLEFT:
            position.setX(self.PREIVIEW_W+self.PREIVIEW_TOLEFT)
        if position.y() < self.PREIVIEW_TOTOP:
            position.setY(self.PREIVIEW_TOTOP)
        elif position.y() > self.PREIVIEW_H+self.PREIVIEW_TOTOP:
            position.setY(self.PREIVIEW_H+self.PREIVIEW_TOTOP)
            
        if dragline.TYPE == 'V':
            position.setY(self.PREIVIEW_TOTOP)
            pos = (((2*position.x()+self.LINE_WEIGHT)/2)-self.PREIVIEW_TOLEFT)
            dragline.xpos = pos/float(self.PREIVIEW_W)
        elif dragline.TYPE == 'H':
            position.setX(self.PREIVIEW_TOLEFT)
            pos = (((2*position.y()+self.LINE_WEIGHT)/2)-self.PREIVIEW_TOTOP)
            dragline.ypos = pos/float(self.PREIVIEW_H)
        else:
            raise Exception
        dragline.move(position)
        self.get_auto_results()
        e.setDropAction(QtCore.Qt.MoveAction)
        e.accept()

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "灰度值分析", None))
        self.previewLabel.setText(_translate("MainWindow", "", None))
        self.autogetLabel.setText(_translate("MainWindow", "自动获取", None))
        self.positionLabel.setText(_translate("MainWindow", "坐标输入", None))
        self.startpointLabel.setText(_translate("MainWindow", "开始坐标", None))
        self.endpointLabel.setText(_translate("MainWindow", "结束坐标", None))
        self.grayValueLabel.setText(_translate("MainWindow", "区域灰度值:", None))
        self.resultLabel.setText(_translate("MainWindow", "点确定以获取结果", None))
        self.exitButton.setText(_translate("MainWindow", "返回", None))
        self.lookAnalyseButton.setText(_translate("MainWindow", "查看分析", None))
        self.okButton.setText(_translate("MainWindow", "确定", None))
        self.switchButton.setText(_translate("MainWindow", "切换模式", None))
        self.tipLabel.setText(_translate("MainWindow", "", None))

        self.okButton.setStyleSheet("QPushButton{border:1px solid lightgray;height:100%;\
            margin-bottom:10px;background:rgb(230,230,230)}"\
            "QPushButton:hover{border-color:green;background:transparent}")
        self.exitButton.setStyleSheet("QPushButton{border-radius:5px;height:80%;margin:5px;\
            background:rgb(220, 20, 60);color:white}"\
            "QPushButton:hover{background:rgb(205, 92, 92)}")
        self.lookAnalyseButton.setStyleSheet("QPushButton{border-radius:5px;height:80%;\
            margin:5px;background:rgb(70,130,180);color:white}"\
            "QPushButton:hover{background:rgb(95, 158, 160)}")
        self.switchButton.setStyleSheet("QPushButton{border-radius:5px;height:80%;margin:5px;\
            background:#90EE90;color:#fff;}"\
            "QPushButton:hover{background:#87CEEB;}")

    def set_avg_gv(self, l_gv, f_gv, r_gv):
        l_gv = round(l_gv, 2)
        f_gv = round(f_gv, 2)
        r_gv = round(r_gv, 2)
        all_gv = round((l_gv + f_gv + r_gv)/3, 2)
        self.left_avg_Label.setText(_translate("MainWindow","左脸灰度值：%s" %(str(l_gv)),None))
        self.frontal_avg_Label.setText(_translate("MainWindow","正脸灰度值：%s" %(str(f_gv)),None))
        self.right_avg_Label.setText(_translate("MainWindow","右脸灰度值：%s" %(str(r_gv)),None))
        self.all_avg_Label.setText(_translate("MainWindow","平均灰度值：%s" %(str(all_gv)),None))

    def set_avg_ir_gv(self, l_ir_gv, f_ir_gv, r_ir_gv):
        l_ir_gv = round(l_ir_gv, 2)
        f_ir_gv = round(f_ir_gv, 2)
        r_ir_gv = round(r_ir_gv, 2)
        all_ir_gv = round((l_ir_gv + f_ir_gv + r_ir_gv)/3, 2)
        self.left_avg_ir_Label.setText(_translate("MainWindow","左脸红外灰度值：%s" %(str(l_ir_gv)),None))
        self.frontal_avg_ir_Label.setText(_translate("MainWindow","正脸红外灰度值：%s" %(str(f_ir_gv)),None))
        self.right_avg_ir_Label.setText(_translate("MainWindow","右脸红外灰度值：%s" %(str(r_ir_gv)),None))
        self.all_avg_ir_Label.setText(_translate("MainWindow","平均红外灰度值：%s" %(str(all_ir_gv)),None))

    def setPreview(self, info):
        self.startpointInput.setPlaceholderText("0A")
        self.endpointInput.setPlaceholderText("3C")
        # 路径
        self.img_path = info.get('path', None)
        self.ir_img_path = info.get('ir_path', None)
        # 图像
        self.orig_img = glahf.read(self.img_path, True)
        self.ir_img = glahf.read(self.ir_img_path, True)

        glahf.write(LINE_TEMP_PATH, \
            glahf.drawlines(self.orig_img, int(self.config['hposcount']), int(self.config['vposcount']), px=1))
        glahf.write(LINE_TEMP_IR_PATH, \
            glahf.drawlines(self.ir_img, int(self.config['hposcount']), int(self.config['vposcount']), px=1))

        # 当前模式
        self.img = self.orig_img
        self.mode = 'ORIG'
        self.previewLabel.setPixmap(QtGui.QPixmap(r''+LINE_TEMP_PATH))
        if self.datas:
            self.set_avg_gv(self.datas['l_gv'], self.datas['f_gv'], self.datas['r_gv'])
            self.set_avg_ir_gv(self.datas['l_ir_gv'], self.datas['f_ir_gv'], self.datas['r_ir_gv'])
        if self.config['calibration'] is True:
            clb = util.clb_array()
            if clb:
                height, width = self.img.shape[:2]
                s_x = clb['start_x'] * width/3 + width/3
                e_x = clb['end_x'] * width/3 + width/3
                s_y = clb['start_y'] * height
                e_y = clb['end_y'] * height
                clb_area = self.img[s_y:e_y, s_x:e_x]
                self.clb_gv = glahf.gray_value(clb_area)
        print "clb:{:>5s}".format(str(self.clb_gv))
        self.get_auto_results()

    @staticmethod
    def dealWithInp(string):
        def gval(str):
            result = 0
            for idx,char in enumerate(str[::-1]):
                c = DICT.get(char)
                result += c*26*idx if idx!=0 else c
            return result

        for i in string:
            if i.isalpha():
                idx = string.index(i)
                b = int(string[0:idx])
                e = gval(string[idx:])-1
                return (str(e),str(b))
        return None

    def getPosition(self):
        lowbound = -1
        starttext = unicode(self.startpointInput.text()) or '0A'
        endtext = unicode(self.endpointInput.text()) or '3C'

        regexp = '^[\d]{1,2}[\A-Z]{1,2}$'
        c = re.compile(regexp)
        if len(re.findall(c,starttext))==0 or len(re.findall(c,endtext))==0:
            tip = "输入格式有误,坐标格式:[纵坐标+横坐标(大写字母)],如5U,28AA"
            self.tipLabel.setText(_translate("MainWindow", tip, None))
            return

        startpoint = self.dealWithInp(starttext)
        endpoint = self.dealWithInp(endtext)

        if int(startpoint[0]) < int(endpoint[0]) <= int(self.config['hposcount']) and\
                                int(startpoint[1]) < int(endpoint[1]) <= int(self.config['vposcount']):
            pass
        else:
            tip = "请输入合理范围，横坐标(A~%s)，纵坐标(0~%s)" %(self.X_HAXIS,self.X_VAXIS)
            self.tipLabel.setText(_translate("MainWindow", tip, None))
            return

        if self.datas:
            self.spliced_img,value =\
                    faceutil.getavggrayvalue(self.img,startpoint,endpoint,self.datas)
        else:
            self.spliced_img,value =\
                    faceutil.getavggrayvalue(self.img,startpoint,endpoint)

        self.resultLabel.setText(str(value))
        pesudo = glahf.gray_to_pseudo(int(value))
        self.area_sp_Color.setStyleSheet("margin:20px 10px;background-color:rgb%s;" %str(pesudo))

        self.tipLabel.setText("")

    def switchVis(self):
        if self.mode == 'ORIG':
            self.mode = 'IR'
            self.previewLabel.setPixmap(QtGui.QPixmap(r'' + LINE_TEMP_IR_PATH))
            self.img = self.ir_img
            self.get_auto_results()
            self.getPosition()

        elif self.mode == 'IR':
            self.mode = 'ORIG'
            self.previewLabel.setPixmap(QtGui.QPixmap(r'' + LINE_TEMP_PATH))
            self.img = self.orig_img
            self.get_auto_results()
            self.getPosition()
        else:
            # exception
            pass

    def getanalyse(self):
        if self.spliced_img is not None:
            faceutil.showplt(self.spliced_img)

    def returnTo(self):
        self.datas = None
        self.close()

    @pyqtSlot() 
    def showMax(self):
        if not self.isMaximized():
            self.showMaximized()
        else:
            self.showNormal()